<template>
  <div>
    <div v-loading="loading" class="change_super">
      <el-form ref="setAction" class="gl_form_mini" label-width="120px" :model="UpdateBusOffline" :rules="UpdateBusOffline_Rules">
        <div class="form_box">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="商家名称" prop="name">
                <el-input v-model="UpdateBusOffline.name" type="text" size="mini" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="当前状态" prop="isOpenOfflinePay">
                <el-select v-model="UpdateBusOffline.isOpenOfflinePay" placeholder="请选择" size="mini" style="width:100%">
                  <el-option v-for="(item, index) in isOpenPay" :key="index" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="收款账户" prop="offlineBeneficiarysName">
                <el-input v-model="UpdateBusOffline.offlineBeneficiarysName" type="text" size="mini" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="开户银行" prop="offlineAccountsWithBank">
                <el-input v-model="UpdateBusOffline.offlineAccountsWithBank" type="text" size="mini" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="开户账号" prop="offlineAccountNumber">
                <el-input v-model="UpdateBusOffline.offlineAccountNumber" type="text" size="mini" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="添加付款码" prop="">
                <div v-for="(item, index) in UpdateBusOffline.busCollectionCodeList" :key="index" class="payment_code gl_mb_10- gl_mr_15">
                  <div>{{ item.name }}</div>
                  <div v-if="item.image" class="img_box">
                    <img :src="getStaticFileUrl(item.image)" alt="">
                    <i class="el-icon-circle-close icon_position" @click="remove(item)" />
                  </div>
                </div>
                <div>
                  <el-button type="warning" size="mini" @click="addPaymentCode()">添加付款码</el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" class="gl_mt_20">
            <el-col :span="8" :offset="8">
              <el-button :loading="buloading" type="primary" class="new_super_submit" size="mini" @click="submitData()">保 存</el-button>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </div>

    <el-dialog title="上传付款码" class="gl_dialog_TitleLine" :visible.sync="dialogVisible" width="660px">
      <div>
        <el-form ref="paymentCode" class="gl_form_mini" label-width="100px" :model="form">
          <el-form-item label="付款码名称" prop="">
            <el-input v-model="form.name" type="text" size="mini" style="width: 300px" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="上传付款码" prop="">
            <el-upload
              :action="action"
              :before-upload="beforeUpload"
              :http-request="upload"
              :auto-upload="true"
              :show-file-list="false"
              :multiple="false"
              accept=".jpg,.png,.jpeg"
            >
              <div v-if="form.image" class="img_code_box show_hover">
                <img :src="getStaticFileUrl(form.image)">
                <i class="el-icon-plus img_hover" />
              </div>
              <i v-else class="el-icon-plus upload" />
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitPaymentCode()">确 定</el-button>
        <el-button size="mini" @click="close()">取 消</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
import { mapState } from 'vuex';
import {
  api_PUT_TradeBusinessesOffline, // 修改线下商家收款信息
  api_POST_TradeBusinessesOffline, // 创建线下商家收款信息
  api_GET_TradeBusinessesOffline // 查询线下商家收款信息
} from '@/extend/api/swaggerApi/app.js';
import validator from '@/lib/validate/index.js';
import {
  BusinessesOfflineInput,
  UpdateBusinessesOfflineInput
} from '@/lib/form/swaggerForm.js';
import { getToken } from '@/lib/auth';
import axios from 'axios';
export default {
  name: 'OfflineCollection',
  props: {
    isShow: {
      type: Boolean
    }
  },
  data() {
    return {
      action: `${WEB_CONFIG.VUE_APP_STATIC_FILE_RUL}/api/upload/image`,
      tokenInfo: getToken(),
      CreateBusOffline: new BusinessesOfflineInput(),
      UpdateBusOffline: new UpdateBusinessesOfflineInput(),
      buloading: false,
      loading: false,
      dialogVisible: false,
      UpdateBusOffline_Rules: { // 字段规则
        name: [
          validator.required('商家名称不能为空')
        ],
        isOpenOfflinePay: [
          { required: true, message: '请设置当前状态', trigger: 'change' }
        ],
        offlineBeneficiarysName: [
          validator.required('收款账户不能为空')
        ],
        offlineAccountsWithBank: [
          validator.required('开户银行不能为空')
        ],
        offlineAccountNumber: [
          validator.required('开户账号不能为空')
        ]
      },
      isOpenPay: [
        {
          label: '启用',
          value: true
        },
        {
          label: '停用',
          value: false
        }
      ],
      removeForms: [],
      form: {
        name: '',
        image: '',
        operate: ''
      },
      file: ''
    };
  },
  computed: {
    ...mapState({
      DelegationId: state => state.user.rootDelegationId
    })
  },
  watch: {
    isShow: {
      handler: function(val) {
        if (val) {
          this.loading = true;
          if (this.UpdateBusOffline) {
            this.UpdateBusOffline.isOpenOfflinePay = true;
          }
          this.findBusiness();
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 查询商家信息
    findBusiness() {
      var that = this;
      that.loading = true;
      api_GET_TradeBusinessesOffline().then(res => {
        that.loading = false;
        if (res) {
          that.UpdateBusOffline = res;
          that.CreateBusOffline = JSON.parse(JSON.stringify(that.UpdateBusOffline));
        }
      }).catch(res => {
        that.loading = false;
        that.$message({
          message: '查询商家信息失败 ' + res.error.message,
          type: 'error'
        });
      });
    },
    // 修改商家信息
    modifyBusiness() {
      var that = this;
      that.buloading = true;
      const form = JSON.parse(JSON.stringify(that.UpdateBusOffline));
      if (that.removeForms.length > 0) {
        for (let i = 0; i < that.removeForms.length; i++) {
          const item = that.removeForms[i];
          form.busCollectionCodeList.push(item);
        }
      }
      if (form.busCollectionCodeList && form.busCollectionCodeList.length > 0) {
        form.busCollectionCodeList = form.busCollectionCodeList.filter(item => {
          return item.operate === 'I' || item.operate === 'D';
        });
      }
      api_PUT_TradeBusinessesOffline(form).then(res => {
        that.buloading = false;
        that.$message({
          message: '收款账号修改成功',
          type: 'success'
        });
        that.removeForms = [];
        that.findBusiness();
      }).catch(res => {
        that.buloading = false;
        var message = res.error.message.split('msg=')[1] ? '：' + res.error.message.split('msg=')[1] : '：' + (res.error.message || '');
        that.$message({
          message: `收款账号修改失败${message}`,
          type: 'error'
        });
      });
    },
    // 创建商家
    creatBuss() {
      var that = this;
      that.buloading = true;
      that.UpdateBusOffline.businessesId = that.DelegationId || '';
      api_POST_TradeBusinessesOffline(that.UpdateBusOffline).then(res => {
        that.buloading = false;
        that.findBusiness();
        that.$message({
          message: '创建商家成功',
          type: 'success'
        });
      }).catch(res => {
        that.buloading = false;
        var message = res.error.message.split('msg=')[1] ? '：' + res.error.message.split('msg=')[1] : '：' + (res.error.message || '');
        that.$message({
          message: `创建商家失败${message}`,
          type: 'error'
        });
      });
    },
    // 修改账户
    submitData() {
      var that = this;
      that.$refs.setAction.validate((valid) => {
        if (valid) {
          that.buloading = true;
          if (!that.CreateBusOffline.name) {
            that.creatBuss();
          } else {
            that.modifyBusiness();
          }
        }
      });
    },
    // 打开上传付款码弹窗
    addPaymentCode() {
      this.dialogVisible = true;
      this.form = {
        name: '',
        image: '',
        operate: ''
      };
    },
    // 删除付款码
    remove(item) {
      item['operate'] = 'D';
      this.removeForms.push(item);
      this.UpdateBusOffline.busCollectionCodeList = this.UpdateBusOffline.busCollectionCodeList.filter(item => {
        return item.operate !== 'D';
      });
    },
    // 上传图片限制
    check(file) {
      const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG或者PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    beforeUpload(file) {
      const checkData = this.check(file);
      if (checkData) {
        this.file = file;
      } else {
        return false;
      }
    },
    // 上传图片
    upload() {
      return new Promise((resolve, reject) => {
        if (!this.file) reject(new Error());
        const form = new FormData();
        form.append('formFile', this.file);
        this.uploadApi(this.action, form).then(res => {
          if (res.status === 200) {
            this.form.image = res.data.tempUrl;
            resolve(res.data);
          } else {
            reject(res.data);
          }
        });
      });
    },
    // 上传图片的api
    uploadApi(url, file) {
      const config = {
        headers: {
          Authorization: 'Bearer ' + this.tokenInfo
        }
      };
      return axios.post(url, file, config);
    },
    // 上传图片回显
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    // 关闭弹窗
    close() {
      this.dialogVisible = false;
    },
    // 保存付款码
    submitPaymentCode() {
      this.UpdateBusOffline.busCollectionCodeList = this.UpdateBusOffline.busCollectionCodeList || [];
      this.form.operate = 'I';
      this.UpdateBusOffline.busCollectionCodeList.push(this.form);
      this.dialogVisible = false;
    }
  }
};
</script>
<style lang="scss" scoped>
.change_super{
  width: 940px;
  margin: 15px;
}
.form_box {
  width: 530px;
  display: inline-block;
}
.new_super_submit{
  width:100%;
}
.img_box {
  width: 120px;
  height: 120px;
  border: 1px solid #DCDFE6;
  position: relative;
}
img {
  width: 100%;
  height: 100%;
}
.icon_position {
  position: absolute;
  right: -4px;
  top: -4px;
  color: #353434;
  font-size: 16px;
  border-radius: 10px;
  background: #fff;
  cursor: pointer;
}
.icon_position:hover {
  color: #1890ff;
}
.payment_code {
  width: 120px;
  display: inline-block;
  font-weight: 600;
}
.upload {
	width: 100px;
	height: 100px;
	cursor: pointer;
	display: inline-block;
	border-radius: 10px;
	text-align: center;
	line-height: 100px;
  border: 1px dashed #c0ccda;
}
.upload:hover {
	border: 1px dashed #409eff;
}
.img_code_box {
  width: 100px;
	height: 100px;
  cursor: pointer;
  display: inline-block;
	border-radius: 6px;
	text-align: center;
  line-height: 100px;
  overflow: hidden;
  border: 1px solid #DCDFE6;
  position: relative;
}
.img_hover {
  width: 100px;
	height: 100px;
  text-align: center;
  font-size: 16px;
  color: #fff;
  border-radius: 6px;
	overflow: hidden;
  position: absolute;
  top: 0;
  left: 0;
  background: rgba(60, 60, 62,0.7);
  line-height: 100px;
  display: none;
}
.show_hover:hover .img_hover{
  display: block;
}
</style>
